const ffmpeg = require('fluent-ffmpeg')
const ffmStaticPath = require('ffmpeg-static')
const ducFSPath = ffmStaticPath.replace('app.asar', 'app.asar.unpacked')
const ffmpegPath = process.env.NODE_ENV === 'development' ? ffmStaticPath : ducFSPath
ffmpeg.setFfmpegPath(ffmpegPath)

// 单独处理视频
function merge_v(videoPath, outputPath) {
    return new Promise((resolve, reject) => {
        ffmpeg()
        .input(videoPath)
        .videoCodec('libx264')
        .on('error', (err) => {
            reject(err) 
        })  
        .on('end', () => {
            resolve('Processing finished !')
        })
        .save(outputPath)
    })
}

// 单独处理音频
function merge_a(audioPath, outputPath) {
    return new Promise((resolve, reject) => {
        ffmpeg()
        .input(audioPath)
        .audioCodec('aac')
        .on('error', (err) => {
            reject(err) 
        })  
        .on('end', () => {
            resolve('Processing finished !')
        })
        .save(outputPath)
    })
}

function merge_v_a_a(videoPathSccren, audioPathSys, audioPathMicr, outputPath) {
    return new Promise((resolve, reject) => {
        ffmpeg()
        .input(videoPathSccren)
        .input(audioPathSys)
        .input(audioPathMicr)
        .complexFilter([
            '[1:a]volume=0.5[a1]',
            '[2:a]volume=2.0[a2]',
            '[a1][a2]amix=inputs=2:duration=longest[a]'])
        .videoCodec('libx264')
        .audioCodec('aac')
        .addOption('-map', '0:v')
        .addOption('-map', '[a]')
        .on('error', (err) => {  
            reject(err)
        })  
        .on('end', () => {  
            resolve('Processing finished !')
        })
        .save(outputPath)
    })
}

function merge_v_a(videoPath, audioPath, outputPath) {
    return new Promise((resolve, reject) => {
        ffmpeg()
        .input(videoPath)
        .input(audioPath)
        .videoCodec('libx264')
        .audioCodec('aac')
        .on('error', (err) => {
            reject(err) 
        })  
        .on('end', () => {
            resolve('Processing finished !')
        })
        .save(outputPath)
    })
}

function merge_a_a(audioPathSys, audioPathMicr, outputPath) {
    return new Promise((resolve, reject) => {
        ffmpeg()
            .input(audioPathSys)
            .input(audioPathMicr)
            .complexFilter('[0:a][1:a]amix=inputs=2:duration=longest[a]')
            .audioCodec('aac')
            .addOption('-map', '[a]')
            .on('error', (err) => {
                reject(err)  
            })  
            .on('end', () => { 
                resolve('Processing finished !')
            })
            .save(outputPath)
    })
}

module.exports = {
    merge_v,
    merge_a,
    merge_v_a,
    merge_a_a,
    merge_v_a_a,
}